package day02am;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author JokerQ
 * @date 2020/8/23 - 17:47
 */
public class Server_v2 {
    public static void main(String[] args) throws IOException {
        /*
        创建一个ServerSocket，用于监听客户端Socket的连接请求
        1、申请端口
        2、接收该端口的所有客户端的连接
        如果端口被占用，会抛出异常：
            Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
         */
        ServerSocket serverSocket = new ServerSocket(8888);
        /*
          每当接收到客户端Socket请求，服务器端也对应产生一个Socket
         */
        System.out.println("ServerSocket等待连接......");
        /*
        开始监听服务器端口，accept是阻塞方法，等待客户端连接，如果没有连接，一直阻塞，
        有链接成功后，结束阻塞，返回socket对象
         */

        Socket socket = serverSocket.accept();
        System.out.println("服务器LocalAddress:"+socket.getLocalAddress());
        System.out.println("服务器LocalPort:"+socket.getLocalPort());
        System.out.println("客户端InetAddress:"+socket.getInetAddress());
        System.out.println("客户端Port:"+socket.getPort());
        System.out.println("客户端连接了！！！");
        //OutputStream out = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "utf-8");
        BufferedReader reader = new BufferedReader(isr);
        //PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"utf-8"),true);
        //阻塞方法，服务器等待客户端说话，等到回车为止
        String str = reader.readLine();
        System.out.println("收到客户端发来："+str);
        //收到后，发送给客户端的回话
       // writer.println("你好啊！！！");
        socket.close();
    }
}
